快慢指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//为空
if(head == NULL || head->next == NULL) {
return false;
}
//快慢指针
ListNode *fastNode = head->next;
ListNode *slowNode = head;
while (fastNode != slowNode) {
if (fastNode->next == NULL || fastNode->next->next == NULL) {
return false;
}
fastNode = fastNode->next->next;
slowNode = slowNode->next;
}
return true;
}
};